<template>
  <div>
    <!-- <div>
      input m2o

      {{ modelValue }} {{ placeholder }}
    </div> -->
    <a-select
      v-model:value="value2"
      allowClear
      label-in-value
      :default-active-first-option="false"
      show-search
      :filter-option="false"
      :show-arrow="false"
      :options="selectOptions"
      :placeholder="placeholder"
      style="width: 90%"
      @search="handleSearch"
      @dropdownVisibleChange="dropdownVisibleChange"
      @change="handleChange"
    >
      <template #dropdownRender="{ menuNode: menu }">
        <v-nodes :vnodes="menu" />
        <template v-if="options.length > 7">
          <a-divider style="margin: 4px 0" />
          <div
            style="padding: 4px 8px; cursor: pointer"
            @mousedown="e => e.preventDefault()"
            @click="searchMore"
          >
            <search-outlined />
            搜索更多
          </div>
        </template>
      </template>
    </a-select>
  </div>
</template>

<script setup>
function VNodes(_, { attrs }) {
  return attrs.vnodes
}

import { computed } from 'vue'

const props = defineProps(['modelValue', 'options', 'placeholder'])
const emit = defineEmits([
  'update:modelValue',
  'dropdown-visible-change',
  'search',
  'change',
  'search-more'
])

const value2 = computed({
  get() {
    return props.modelValue
      ? { value: props.modelValue.id, label: props.modelValue.display_name }
      : undefined
    // { value: undefined, label: undefined }
  },
  set(val) {
    if (val) {
      const { value, label } = val
      const label2 = label.trim()
      emit('update:modelValue', { id: value, display_name: label2 })
    } else {
      emit('update:modelValue', { id: null, display_name: null })
    }
  }
})

const selectOptions = computed(() => {
  return props.options.slice(0, 7).map(item => {
    return { value: item[0], label: item[1] }
  })
})

async function handleSearch(val) {
  emit('search', val)
}

function dropdownVisibleChange(open) {
  if (open) {
    emit('dropdown-visible-change')
  }
}

function handleChange(val) {
  //   console.log(val)
  if (val) {
    const { value, label } = val
    const label2 = label.trim()
    emit('change', { id: value, display_name: label2 })
  } else {
    emit('change', { id: null, display_name: null })
  }
}

function searchMore() {
  emit('search-more')
}
</script>

<style scoped></style>
